const { getCurrentTimestamp } = require('./utils/time');

/**
 * @Description 写入本地缓存
 * @author 53010
 * @date 2020/7/27 15:38
 * @param {String} key 缓存键
 * @param {Object} value 缓存数据
 * @param {Number} expire 有效时间(秒)
 */
async function writeCache(key, value, expire) {
    await checkCacheStorage();
    await uni.setStorageSync(key, {
        data: value,
        expire: getCurrentTimestamp() + expire
    });
    return 1;
}

/**
 * 读取本地缓存
 * @param key
 * @returns {Promise<*>}
 */
async function readCache(key) {
    await checkCacheStorage();
    const result = uni.getStorageSync(key);
    if (!result.data || !result.expire) {
        throw new Error(`no data for ${key}`);
    }
    if (getCurrentTimestamp() > result.expire) {
        uni.removeStorageSync(key);
        throw new Error(`has expired for ${key}`);
    }
    return result.data;
}

async function checkCacheStorage() {
    const storageInfo = uni.getStorageInfoSync();
    if (storageInfo.currentSize + 1000 > storageInfo.limitSize) {
        uni.clearStorageSync();
    }
}

module.exports = {
    writeCache,
    readCache
};
